package com.bdv.md.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl.CriterionEntry;
import org.springframework.stereotype.Repository;

import com.bdv.md.dao.MapTblDao;
import com.bdv.md.model.MapTbl;

@Repository
public class MapTblDaoImpl extends AbstractDaoImpl<MapTbl, Integer> implements MapTblDao {

	public MapTblDaoImpl() {
		super(MapTbl.class);
	}

	public MapTbl findByMeterAndType(String meterId, String tipeMeter, Integer tipePu) {

    	List<Criterion> criterions = new ArrayList<Criterion>();
    	criterions.add(Restrictions.eq("meterId", meterId));
    	criterions.add(Restrictions.eq("tipeMeter", tipeMeter));
    	criterions.add(Restrictions.eq("tipePu", tipePu));
    	
    	List<MapTbl> mapTbls = findByCriterias(criterions);
    	
        return mapTbls == null || mapTbls.isEmpty() ? null : mapTbls.get(0);
	}

	public MapTbl findByMeterAndMsisdn(String meterId, String msisdn) {

    	List<Criterion> criterions = new ArrayList<Criterion>();
    	criterions.add(Restrictions.eq("meterId", meterId));
    	criterions.add(Restrictions.eq("msisdn", msisdn));
    	
    	List<MapTbl> mapTbls = findByCriterias(criterions);
    	
        return mapTbls == null || mapTbls.isEmpty() ? null : mapTbls.get(0);
	}

	public List<MapTbl> findAll() {
    	List<Criterion> criterions = new ArrayList<Criterion>();
    	List<MapTbl> mapTbls = findByCriterias(criterions);
		return mapTbls;
	}
	
	public MapTbl delete(String msisdn,String meterId){

    	List<Criterion> criterions = new ArrayList<Criterion>();
    	criterions.add(Restrictions.eq("meterId", meterId));
    	
    	List<MapTbl> mapTbls = findByCriterias(criterions);
    	
        MapTbl map = mapTbls == null || mapTbls.isEmpty() ? null : mapTbls.get(0);

        if(map!=null){
        	delete(map);
        }else{
        	criterions = new ArrayList<Criterion>();
        	criterions.add(Restrictions.eq("msisdn", msisdn));
        	
        	mapTbls = findByCriterias(criterions);
        	
            map = mapTbls == null || mapTbls.isEmpty() ? null : mapTbls.get(0);
            if(map!=null){
            	delete(map);
            	map.setMapId(null);
            }
        }
        
        return map;
	}
}
